//===============================================================================
// Microsoft patterns & practices
// Web Client Software Factory
//===============================================================================
// Copyright � Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using Microsoft.Practices.CompositeWeb;
using Microsoft.Practices.ObjectBuilder;
using MVPComposibility.ContactManager.DomainModel;
using System.Collections.Generic;
using MVPComposibility.ContactManager.Views.ContactDetails;

namespace MVPComposibility.ContactManager.Views.ContactDetails
{
	public class ContactDetailsPresenter : Presenter<IContactDetailsView>
	{
		private ContactDetailsModel _model;

		[CreateNew]
		public ContactDetailsModel Model
		{
			get { return _model; }
			set
			{
				if (_model != null)
				{
					_model.ContactChanged -= Model_ContactChanged;
				}
				_model = value;
				if (_model != null)
				{
					_model.ContactChanged += Model_ContactChanged;
				}
			}
		}

		public override void OnViewInitialized()
		{
			LoadFromModel();
		}


		public override void OnViewLoaded()
		{
			WireUpEvents();
			LoadModelFromView();
		}

		private void WireUpEvents()
		{
			View.DiscardChanges += View_DiscardChanges;
			View.SaveChanges += View_SaveChanges;
		}

		private void LoadFromModel()
		{
			if (_model.Contact != null)
			{
				View.ContactId = _model.EditedContact.Id;
				View.ContactName = _model.EditedContact.Name;
				View.Addresses = _model.EditedContact.Addresses;
			}
			else
			{
				View.ContactId = 0;
				View.ContactName = string.Empty;
				View.Addresses = new List<Address>();
			}
		}

		private void LoadModelFromView()
		{
			if (_model.Contact != null)
			{
				_model.EditedContact.Name = View.ContactName;
			}
		}

		void Model_ContactChanged(object sender, System.EventArgs e)
		{
			LoadFromModel();
		}

		void View_SaveChanges(object sender, System.EventArgs e)
		{
			LoadModelFromView();
			_model.EditComplete();
		}

		void View_DiscardChanges(object sender, System.EventArgs e)
		{
			_model.EditCancel();
			LoadFromModel();
		}
	}
}